package org.ezplatform.office.meeting.search.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.component.permission.service.CmpPermissionService;
import org.ezplatform.component.permission.utils.CmpPermissionConstant;
import org.ezplatform.component.popuser.service.CmpPopUserOrgName;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.entity.MeetingScope;
import org.ezplatform.office.meeting.info.service.ApplyRecordService;
import org.ezplatform.office.meeting.info.service.MeetingScopeService;
import org.ezplatform.office.meeting.search.dao.SearchDao;
import org.ezplatform.office.meeting.search.entity.ApplyRecordExport;
import org.ezplatform.office.meeting.setting.serve.service.ServeSetService;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("searchService")
@Transactional
public class SearchService extends BaseService<ApplyRecord, String>{
	private final static Logger LOGGER = LoggerFactory.getLogger(SearchService.class);
    @Autowired
    private SearchDao dao;
    
    @Autowired
    private OrgApiService orgApiService;
    @Lazy
    @Autowired
    private ServeSetService serveSetService;
    @Lazy
    @Autowired
    private PopUserScopeUtilService popScopeService;
    @Lazy
    @Autowired
    private MeetingScopeService meetingScopeService;
    @Lazy
    @Autowired
    private ApplyRecordService applyRecordService;
    
    @Autowired
	private CmpPermissionService cmpPermissionService;
    
    @Autowired
    private CmpPopUserOrgName cmpPopUserOrgName;
    
    @Autowired
    private RestClient restClient;
    
    private int currentPageNum = 0;
    private int pageSizeNum = 0;
    private int startLimitNum = 0;
    
    @Override
    protected JpaBaseDao<ApplyRecord, String> getEntityDao() {
        return dao;
    }

    /**
     * 查询会议列表数据
     * @param localPageable
     * @param corpId
     * @param name
     * @param status
     * @param type
     * @return
     */
    public Page getSearchList(Pageable localPageable, String corpId, String name,String status,int type,int isAdminRole,String token) {
    	LOGGER.debug("-----getSearchList----");
    	WebUser user = WebUtils.getCurrentUser();
        String userId = user.getUserId();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer(" ");
        sql.append("select t1.id dataid,t1.name,t1.startTime,t1.endTime,t1.createdUserId as id,t1.memoScope,t1.status,t1.emceeUserId,t1.is_signed,");
//        sql.append("t1.signed_type,t1.memoUserId,t1.memoInfoId,t1.boardroomName,t1.address,t1.boardroomId,t1.isApprove,t1.createdDate,t1.isView,t1.userId," + isAdminRole + " is_admin_role from (");
        sql.append("t1.signed_type,t1.memoUserId,t1.memoInfoId,t1.boardroomName,t1.address,t1.boardroomId,t1.isApprove,t1.createdDate,t1.isView " + " from (");
        
        sql.append("select omar.id,omar.name,omar.start_time startTime,omar.end_time endTime,omar.createdBy createdUserId,omar.is_signed,");
        sql.append("omar.signed_type,omar.status,omar.memo_user memoScope,oms1.scopeValue emceeUserId,oms2.scopeValue memoUserId,");
//        sql.append("ommi.id memoInfoId,ombs.name boardroomName,omar.address,omar.boardroom_id boardroomId,ombs.is_approve isApprove,omar.createdDate,ommui.is_view isView,:userId as userId,");
        sql.append("ommi.id memoInfoId,ombs.name boardroomName,omar.address,omar.boardroom_id boardroomId,ombs.is_approve isApprove,omar.createdDate,ommui.is_view isView,");
        sql.append("omar.createdOrg,omar.createdBy from ( ");
        
        sql.append("select omar.id,omar.name,omar.start_time ,omar.end_time ,omar.createdBy ,omar.is_signed,");
        sql.append("omar.signed_type,omar.status,omar.memo_user ,");
        sql.append("omar.address,omar.boardroom_id ,omar.createdDate,");
        sql.append("omar.createdOrg,omar.emcee_user ");
        
        sql.append("from oa_meeting_apply_record omar ");
        sql.append("where omar.corp_id =:corpId");
        if(type==0){//我发起的会议
            sql.append(" and omar.createdBy in (:userId) and omar.status not in ('-1', '0', '6', '2') ");//在流程中的会议和草稿箱中的会议不可显示，已驳回的会议不可显示
        }else if(type==1){//我参与的会议
        	List<String> unitorgList = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
            if(unitorgList==null){
                unitorgList = new ArrayList<String>();
            }
            unitorgList.add(userId);
            sql.append(" and ((omar.status ='3' and omar.createdBy = :userId) or omar.status in ('1','4','5'))");
            sql.append(" and ");
            sql.append(" (omar.emcee_user in (select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in (:userId))");
            sql.append(" or omar.memo_user in (select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in (:userId))");
            sql.append(" or omar.attend_user in (select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in (:unitorgList)))");
            paramMap.put("unitorgList", unitorgList);
        }else if(type==666){//我发起的会议和我参与的会议合并
        	List<String> unitorgList = new ArrayList<>();//this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
//            if(unitorgList==null){
//                unitorgList = new ArrayList<String>();
//            }
            unitorgList.add(userId);
            sql.append(" and ((omar.createdBy in (:userId) and omar.status not in ('-1', '0', '6', '2')) ");
            sql.append(" or (((omar.status ='3' and omar.createdBy = :userId) or omar.status in ('1','4','5'))");
            sql.append(" and ");
            sql.append(" (omar.emcee_user in (select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in (:userId))");
            sql.append(" or omar.memo_user in (select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in (:userId))");
            sql.append(" or omar.attend_user in (select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in (:unitorgList))");
            //查询个人群组
//            sql.append(" or (exists (select 1 from oa_personal_group_user opgu where opgu.user_id=:userId and exists (select 1 from oa_meeting_apply_record_scope oms where oms.fieldDataValue=omar.attend_user and oms.scopeType='personalGroup' and oms.deleteflag=0 and oms.fieldData='attend_user' and oms.scopevalue=opgu.group_id)))");
            sql.append(")))");
            
            paramMap.put("unitorgList", unitorgList);
        }else{
        	sql.append(cmpPermissionService.getBusinessScopeSql("omar", user, "meeting:meeting:03"));
            sql.append(" and omar.status not in ('-1', '0', '6', '2') ");//在流程中的会议和草稿箱中的会议不可显示，已驳回的会议不可显示
        }
        
        if(StringUtils.isNotBlank(name)){
            sql.append(" and omar.name like :name");
            paramMap.put("name", "%"+name+"%");
        }
        if(StringUtils.isNotBlank(status)){
            sql.append(" and omar.status = :status");
            paramMap.put("status", status);
        }
        sql.append(" and omar.is_cycle = 0 and omar.is_sync = 1 ) omar ");
        
        sql.append("left join oa_meeting_apply_record_scope oms1 on omar.emcee_user = oms1.fieldDataValue ");
        //sql.append("left join sys_user su1 on oms1.scopeValue = su1.id ");
        sql.append("left join oa_meeting_apply_record_scope oms2 on omar.memo_user = oms2.fieldDataValue ");
        //sql.append("left join sys_user su2 on oms2.scopeValue = su2.id ");
        sql.append("left join oa_meeting_boardroom_set ombs on omar.boardroom_id = ombs.id ");
        sql.append("left join oa_meeting_memo_info ommi on omar.id = ommi.apply_record_id ");
        sql.append("left join oa_meeting_memo_user_info ommui on ommi.id = ommui.memo_id and ommui.memo_user_id = :userId ");
        
        paramMap.put("corpId", corpId);
        paramMap.put("userId", userId);
        
        
        sql.append(") t1 where 1=1 ");
        
//        String perSql = cmpPermissionService.getBusinessScopeSql("t1", user, "meeting:meeting:03");
//		LOGGER.debug("---perSql:"+perSql);
//		sql.append(perSql);
		LOGGER.debug("---sql:"+sql);
		
        List<PropertyFilter> buildFilters = new ArrayList<>();
        String sqlStr = PropertyFilter.getSqlByFilterAndPageable("t1", sql.toString(), "t1.startTime desc, t1.createdDate desc", buildFilters, localPageable);
        LOGGER.debug("---sqlStr:"+sqlStr);
        Page<Map> localPage = this.findByPageNativeSQL(localPageable, sqlStr, paramMap);
        List<Map>reList=localPage.getContent();
        Map<String, String> permissionInfoMap = new HashMap<String, String>();
		// map格式：key-权限编码，value-操作标识
		permissionInfoMap.put("meeting:meeting:maintain", CmpPermissionConstant.PERMISSION_NAME_CAN_EDIT);
		cmpPermissionService.processBaseListByDataScope(reList, user, permissionInfoMap, "user");
		String createdUserId="";
        for(Map temp:reList) {
        	String emceeUserId=(String)temp.get("emceeUserId");
        	String emceeUserName = cmpPopUserOrgName.getUserNameById(emceeUserId);
        	String memoUserId=(String)temp.get("memoUserId");
        	String memoUserName = cmpPopUserOrgName.getUserNameById(memoUserId);
        	temp.put("emceeUserName", emceeUserName);
        	temp.put("memoUserName", memoUserName);
        	temp.put("userId", userId);
        	temp.put("is_admin_role", isAdminRole);
        	createdUserId=String.valueOf(temp.get("id"));
        	temp.put("id", temp.get("dataid"));
        	temp.put("createdUserId", createdUserId);
        }
        return localPage;
    }

    /**
     * 查询单个周期内的会议
     * @param localPageable
     * @param cycleId
     * @param corpId
     * @param startTime
     * @param endTime
     * @param status
     * @param userId
     * @param isAdminRole
     * @return
     */
    public Page getCycleMeetingForm(Pageable localPageable, String cycleId, String corpId, String startTime, String endTime, String status, 
    		String userId, int isAdminRole, String token, String type) {
    	Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select t1.id,t1.name,t1.startTime,t1.endTime,t1.createdUserId,t1.status,t1.emceeUserId,t1.emceeUserName,t1.is_signed,t1.memoUserName,");
        sql.append("t1.signed_type,t1.memoUserId,t1.memoInfoId,t1.boardroomName,t1.address,t1.boardroomId,t1.isApprove,t1.createdDate,t1.isView,t1.userId," + isAdminRole + " is_admin_role from (");
        sql.append("select omar.id,omar.name,omar.start_time startTime,omar.end_time endTime,omar.createdBy createdUserId,omar.is_signed,");
        sql.append("omar.signed_type,omar.status,su1.id emceeUserId,su1.user_name emceeUserName,su2.id memoUserId,su2.user_name memoUserName,");
        sql.append("ommi.id memoInfoId,ombs.name boardroomName,omar.address,omar.boardroom_id boardroomId,ombs.is_approve isApprove,omar.createdDate,ommui.is_view isView,'"+userId+"' as userId ");
        sql.append("from oa_meeting_apply_record omar ");
        sql.append("left join oa_meeting_apply_record_scope oms1 on omar.emcee_user = oms1.fieldDataValue ");
        sql.append("left join sys_user su1 on oms1.scopeValue = su1.id ");
        sql.append("left join oa_meeting_apply_record_scope oms2 on omar.memo_user = oms2.fieldDataValue ");
        sql.append("left join sys_user su2 on oms2.scopeValue = su2.id ");
        sql.append("left join oa_meeting_boardroom_set ombs on omar.boardroom_id = ombs.id ");
        sql.append("left join oa_meeting_memo_info ommi on omar.id = ommi.apply_record_id ");
        sql.append("left join oa_meeting_memo_user_info ommui on ommi.id = ommui.memo_id and ommui.memo_user_id = :userId ");
        sql.append("where omar.corp_id =:corpId and omar.is_cycle=1 and omar.cycle_id=:cycleId and omar.is_sync=1");
        sql.append(" and omar.status not in ('-1', '0', '6', '2') ");
        if(StringUtils.isNotBlank(startTime)){
            sql.append(" and omar.start_time >= :startTime");
            paramMap.put("startTime", startTime + " 00:00");
        }
        if(StringUtils.isNotBlank(endTime)){
            sql.append(" and omar.start_time <= :endTime");
            paramMap.put("endTime", endTime + " 59:59");
        }
        if(StringUtils.isNotBlank(status)){
            sql.append(" and omar.status = :status");
            paramMap.put("status", status);
        }
        if("self".equals(type)) {//只查自己参与的周期会议
        	sql.append(" and (omar.createdBy=:userId ");
        	sql.append("	or (omar.emcee_user IN (:emceeScopeList)");
    		sql.append("		 or omar.memo_user IN (:memoScopeList)");
    		sql.append("		 or omar.attend_user IN (:attendScopeList)))");
            List<String> list = orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
    		list.add(userId);
    		List<String> emceeScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "emcee_user");
    		List<String> memoScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "memo_user");
    		List<String> attendScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "attend_user");
    		paramMap.put("emceeScopeList", CollectionUtils.isNotEmpty(emceeScopeList) ? emceeScopeList : "");
    		paramMap.put("memoScopeList", CollectionUtils.isNotEmpty(memoScopeList) ? memoScopeList : "");
    		paramMap.put("attendScopeList", CollectionUtils.isNotEmpty(attendScopeList) ? attendScopeList : "");
        }
        sql.append(") t1 where 1=1 ");
        paramMap.put("corpId", corpId);
        paramMap.put("userId", userId);
        paramMap.put("cycleId", cycleId);
        List<PropertyFilter> buildFilters = new ArrayList<>();
        String sqlStr = PropertyFilter.getSqlByFilterAndPageable("t1", sql.toString(), "t1.startTime desc, t1.createdDate desc", buildFilters, localPageable);
        Page<Map> localPage = this.findByPageNativeSQL(localPageable, sqlStr, paramMap);
        return localPage;
    }
    
    /**
     * 查询周期会议
     * @param localPageable
     * @param corpId
     * @param name
     * @param status
     * @return
     */
    public Page getCycleMeeting(Pageable localPageable, String type, String corpId, String name, String cycleType, 
    		String userId, int isAdminRole, String token,WebUser webUser) {
    	long time=System.currentTimeMillis();
    	LOGGER.debug("-----getCycleMeeting----");
    	Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select tt.id,tt.name,tt.start_time,tt.boardroom_name,tt.address,tt.boardroomId,");
        sql.append(" tt.cycle_type,tt.cycle_end_time,tt.emcee_user_id,tt.memo_user_id,tt.createdBy,'" + userId + "' userId," + isAdminRole + " is_admin_role");
        sql.append(" from (");
        sql.append(" select t.id,t.name,min( t.start_time ) start_time,t.boardroom_name,t.address,t.boardroomId,");
        sql.append(" t.cycle_type,t.cycle_end_time,t.emcee_user_id,t.memo_user_id,t.createdBy");
        sql.append(" from (");
        
        sql.append(" select ar.cycle_id as id,ar.name,ar.start_time,ar.end_time,mb.name boardroom_name,ar.address,ar.boardroom_id boardroomId,");
        sql.append(" ar.cycle_type,ar.cycle_end_time,ms.scopeValue emcee_user_id,ms2.scopeValue memo_user_id,ar.createdBy,ar.createdOrg");
        sql.append(" from (");
        
        sql.append(" select ar.cycle_id,ar.name,ar.start_time,ar.end_time,ar.address,ar.boardroom_id,");
        sql.append(" ar.cycle_type,ar.cycle_end_time,ar.createdBy,ar.createdOrg,ar.emcee_user,ar.memo_user,ar.createdDate");
        sql.append(" from oa_meeting_apply_record ar");
        
        sql.append(" where ar.corp_id=:corpId and ar.is_sync=1 and ar.is_cycle = 1 AND ar.cycle_id IS NOT NULL ");
        if(StringUtils.isNotBlank(name)) {
        	sql.append(" and ar.name like :name");
        	paramMap.put("name", "%"+name+"%");
        }
        if(StringUtils.isNotBlank(cycleType)) {
        	sql.append(" and ar.cycle_type = :cycleType");
        	paramMap.put("cycleType", cycleType);
        }
        if("self".equals(type)) {//只查自己参与的周期会议
        	sql.append(" and (ar.createdBy=:userId ");
        	sql.append("	or (ar.emcee_user IN (:emceeScopeList)");
    		sql.append("		 or ar.memo_user IN (:memoScopeList)");
    		sql.append("		 or ar.attend_user IN (:attendScopeList)))");
            List<String> list = new ArrayList<String>(1);//orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
    		list.add(userId);
    		
    		LOGGER.debug("-----zhaozy1:"+(System.currentTimeMillis()-time));
    		time=System.currentTimeMillis();
    		List<String> emceeScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "emcee_user");
    		LOGGER.debug("-----zhaozy2:"+(System.currentTimeMillis()-time));
    		time=System.currentTimeMillis();
    		List<String> memoScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "memo_user");
    		LOGGER.debug("-----zhaozy3:"+(System.currentTimeMillis()-time));
    		time=System.currentTimeMillis();
    		List<String> attendScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "attend_user");
    		LOGGER.debug("-----zhaozy4:"+(System.currentTimeMillis()-time));
    		time=System.currentTimeMillis();
    		paramMap.put("userId", userId);
    		paramMap.put("emceeScopeList", CollectionUtils.isNotEmpty(emceeScopeList) ? emceeScopeList : "");
    		paramMap.put("memoScopeList", CollectionUtils.isNotEmpty(memoScopeList) ? memoScopeList : "");
    		paramMap.put("attendScopeList", CollectionUtils.isNotEmpty(attendScopeList) ? attendScopeList : "");
        }
        sql.append(" )ar");
        
//        sql.append(" join (select min( start_time ) start_time, cycle_id FROM oa_meeting_apply_record where is_cycle = 1 and cycle_id is not null group by cycle_id) t on ar.cycle_id=t.cycle_id and ar.start_time=t.start_time");
        sql.append(" left join oa_meeting_boardroom_set mb on ar.boardroom_id=mb.id");
        sql.append(" left join oa_meeting_apply_record_scope ms on ar.emcee_user = ms.fieldDataValue");
//        sql.append(" left join sys_user su on su.id=ms.scopeValue");
        sql.append(" left join oa_meeting_apply_record_scope ms2 on ar.memo_user = ms2.fieldDataValue");
//        sql.append(" left join sys_user su2 on su2.id=ms2.scopeValue");
        
        sql.append(" ORDER BY ar.start_time desc, ar.createdDate desc");
        sql.append(" ) t where 1=1 ");
        //权限范围
        String perSql = cmpPermissionService.getBusinessScopeSql("t", webUser, "meeting:meeting:03");
		LOGGER.debug("---perSql:"+perSql);
		sql.append(perSql);
		sql.append("GROUP BY t.id,t.NAME,t.boardroom_name,t.address,t.boardroomId,t.emcee_user_id,t.memo_user_id,t.cycle_type,t.cycle_end_time,t.createdBy");
        sql.append(" ) tt "); 
        paramMap.put("corpId", corpId);

        LOGGER.debug("---sql:"+sql);
        LOGGER.debug("-----zhaozy5:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
        String sqlStr = PropertyFilter.getSqlByFilterAndPageable("tt", sql.toString(), "tt.start_time desc", new ArrayList<>(), localPageable);
        LOGGER.debug("-----zhaozy6:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
        Page<Map> localPage = this.findByPageNativeSQL(localPageable, sqlStr, paramMap);
        LOGGER.debug("-----zhaozy7:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
        List<Map> reContent=localPage.getContent();
//        String dataId=null;
        for(Map temp:reContent) {
//        	dataId= (String)temp.get("dataid");
//        	temp.put("createdBy", temp.get("id"));
//        	temp.put("id", dataId);
        	String emcee_user_id=(String)temp.get("emcee_user_id");
        	String emceeUserName = cmpPopUserOrgName.getUserNameById(emcee_user_id);
        	temp.put("emcee_user", emceeUserName);
        	String memo_user_id=(String)temp.get("memo_user_id");
        	String memoUserName = cmpPopUserOrgName.getUserNameById(memo_user_id);
        	temp.put("memo_user", memoUserName);
        }
        LOGGER.debug("-----zhaozy8:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
        return localPage;
    }
    
    /**
     * 查询预约会议室信息列表数据
     * @param localPageable
     * @param corpId
     * @param name
     * @param status
     * @return
     */
    public Page getSearchApplyList(Pageable localPageable, String corpId, String boardroomName, String startTime, String endTime,
    		String bpmStatus, List<String> readList) {
    	LOGGER.info("----getSearchApplyList----");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer(" ");
        sql.append("select omar.id,omar.name,omar.start_time startTime,omar.end_time endTime,omar.createdBy,omar.apply_user_name applyUserName,");
        sql.append("omar.status,ombs.name boardroomName,omar.address,omar.boardroom_id boardroomId,arp.NAME_ as procName,omar.formid as formKey,ahp.PROC_INST_ID_ as processInstanceId, ");
        sql.append("ahp.END_TIME_ as bpmEndTime,ahp.PROC_DEF_ID_ as procDefId,ahp.EXT_PROCESSSTATUS bpmStatus ");
        sql.append("from oa_meeting_apply_record omar ");
        sql.append("left join oa_meeting_boardroom_set ombs on omar.boardroom_id = ombs.id ");
        
        sql.append(" join act_hi_procinst ahp on omar.id = ahp.BUSINESS_KEY_ and ahp.PROC_INST_ID_ is not null ");
        if(StringUtils.isNotBlank(bpmStatus)){
            sql.append(" and ahp.EXT_PROCESSSTATUS = :bpmStatus ");
            paramMap.put("bpmStatus", bpmStatus);
        }
        sql.append(" join act_re_procdef arp on ahp.PROC_DEF_ID_ = arp.ID_ ");
        if (readList != null && readList.size() > 0) {
            sql.append(" and arp.KEY_ in (:readList) ");
            paramMap.put("readList", readList);
        }else {
        	sql.append(" and arp.KEY_ ='' ");
        }
        
        sql.append("left join act_ru_variable arv on ahp.PROC_INST_ID_ = arv.PROC_INST_ID_ and arv.name_ = 'ext_indraft' ");
        sql.append("where omar.corp_id =:corpId and arv.ID_ is null ");
        paramMap.put("corpId", corpId);

        if(StringUtils.isNotBlank(boardroomName)){
            sql.append(" and ombs.name like :boardroomName ");
            paramMap.put("boardroomName", "%"+boardroomName+"%");
        }

        //开始结束时间
        if(StringUtils.isNotBlank(startTime)){
            sql.append(" and omar.start_time >= :startTime ");
            paramMap.put("startTime", startTime + " 00:00");
        }
        if(StringUtils.isNotBlank(endTime)){
            sql.append(" and omar.end_time <= :endTime ");
            paramMap.put("endTime", endTime + " 59:59");
        }
        
        

        //会议状态查询
//        if("0".equals(applyStatus)){//申请中
//            sql.append(" and ahp.END_TIME_ is null and omar.status = '0' ");
//        }else if("1".equals(applyStatus)){//未召开
//            sql.append(" and ahp.END_TIME_ is not null and omar.status = '1' ");
//        }else if("2".equals(applyStatus)){//已驳回
//            sql.append(" and ahp.END_TIME_ is null and omar.status = '2' ");
//        }else if("3".equals(applyStatus)){//已取消
//            sql.append(" and omar.status in ('-1', '3') ");
//        }else if("4".equals(applyStatus)){//进行中
//            sql.append(" and omar.status in ('4') ");
//        }else if("5".equals(applyStatus)){//已结束
//            sql.append(" and omar.status in ('5') ");
//        }

        sql.append("order by omar.start_time desc, omar.createdDate desc ");
        LOGGER.info("--sql："+sql);
        List<PropertyFilter> buildFilters = new ArrayList<>();
        String sqlStr = PropertyFilter.getSqlByFilterAndPageable("", sql.toString(), "", buildFilters, localPageable);
        Page<Map> localPage = this.findByPageNativeSQL(localPageable, sqlStr, paramMap);
        return localPage;
    }
    
    /**
     * 查询会议list列表数据信息
     * @param currentPage
     * @param pageSize
     * @param userId
     * @param corpId
     * @param condition 
     * @param type 0:
     * @return
     */
    public List<Map> getApplyRecordList(String currentPage, String pageSize, String userId,
            String corpId, String condition, int type,String isCountType,String token) {
        List<Map> list = new ArrayList<>();
       StringBuffer sql = new StringBuffer(" ");
       Map<String, Object> paramMap = new HashMap<String, Object>();
       paramMap.put("corpId", corpId);
       paramMap.put("userId", userId);
       sql.append("select omar.id,omar.name applyRecordName,omar.start_time startDateTime,omar.end_time endDateTime,");
       sql.append("omar.createdBy createdUserId,omar.status,ombs.name boardroomName,omar.address,omar.boardroom_id boardroomId from oa_meeting_apply_record omar ");
       sql.append("left join oa_meeting_boardroom_set ombs on omar.boardroom_id = ombs.id ");
       sql.append(" where omar.corp_id =:corpId and omar.is_cycle=0 and omar.is_sync=1");
       if(type == 0){//我发起的会议
    	   sql.append(" and omar.createdBy =:userId and omar.status not in ('-1', '0', '6', '2') ");
       }else{//我参与的会议
    	   List<String> unitorgList = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
    	   if(unitorgList==null){
               unitorgList = new ArrayList<String>();
           }
           unitorgList.add(userId);
           paramMap.put("unitorgList", unitorgList);
           sql.append(" and ((omar.status ='3' and omar.createdBy =:userId) or omar.status in ('1','4','5'))");
           sql.append(" and");
           sql.append(" (omar.emcee_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
           sql.append(" or omar.memo_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
           sql.append(" or omar.attend_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in(:unitorgList)))");
       }
       
       if(StringUtils.isNotBlank(condition)){
           sql.append(" and omar.name like :condition ");
           paramMap.put("condition", "%"+condition+"%");
       }
       sql.append(" order by omar.start_time desc, omar.createdDate desc");
	   	if(isCountType.equals("0")){
	        if(StringUtils.isNotBlank(currentPage)){
	            this.currentPageNum = Integer.valueOf(currentPage);
	        }
	        if(StringUtils.isNotBlank(pageSize)){
	            this.pageSizeNum = Integer.valueOf(pageSize);
	        }
	       this.startLimitNum= (this.currentPageNum-1) * this.pageSizeNum;
	        list = super.findByListNativeQuery(sql.toString(), "", paramMap, this.startLimitNum, this.pageSizeNum);
	    }else{
            list = super.findByListNativeQuery(sql.toString(), "", paramMap);
        }

        if(list!=null && list.size()>0){
        	Locale localeCN = Locale.SIMPLIFIED_CHINESE;
            SimpleDateFormat format = new SimpleDateFormat("E",localeCN);
        	for(Map<String,Object> map : list){
                String startDateTime = String.valueOf(map.get("startDateTime"));
                String endDateTime = String.valueOf(map.get("endDateTime"));
                if(startDateTime != null){
                	String week = format.format(DateUtils.parseDate(startDateTime));
                    String day = DateUtils.formatDate(DateUtils.parseDate(startDateTime), "MM")+"."+DateUtils.formatDate(DateUtils.parseDate(startDateTime), "dd");
                    map.put("startTime", startDateTime.split(" ")[1]);
                    map.put("endTime", endDateTime.split(" ")[1]);
                    map.put("startDate", startDateTime.substring(5,startDateTime.length()));
                    map.put("endDate", endDateTime.substring(5,endDateTime.length()));
                    map.put("day", day);
                    map.put("week", week);
                }
            }
        }
        return list;
    }

    /**
     * 查询会议list列表数据信息(我发起的我参加的合并)
     * @param currentPage
     * @param pageSize
     * @param userId
     * @param corpId
     * @param condition 
     * @return
     */
    public List<Map> getApplyRecordListOfMine(String currentPage, String pageSize, String userId,
            String corpId, String condition, String token) {
       StringBuffer sql = new StringBuffer(" ");
       Map<String, Object> paramMap = new HashMap<String, Object>();
       paramMap.put("corpId", corpId);
       paramMap.put("userId", userId);
       sql.append("select omar.id,omar.name applyRecordName,omar.start_time startDateTime,omar.end_time endDateTime,");
       sql.append("omar.createdBy createdUserId,omar.status,ombs.name boardroomName,omar.address,omar.boardroom_id boardroomId from oa_meeting_apply_record omar ");
       sql.append("left join oa_meeting_boardroom_set ombs on omar.boardroom_id = ombs.id ");
       sql.append(" where omar.corp_id =:corpId and omar.is_cycle=0 and omar.is_sync=1");
	   List<String> unitorgList = new ArrayList<String>();//this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
       unitorgList.add(userId);
       paramMap.put("unitorgList", unitorgList);
       sql.append(" and ((((omar.status ='3' and omar.createdBy =:userId) or omar.status in ('1','4','5'))");
       sql.append(" and");
       sql.append(" (omar.emcee_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
       sql.append(" or omar.memo_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
       sql.append(" or omar.attend_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in(:unitorgList))))");
       sql.append(" or (omar.createdBy =:userId and omar.status not in ('-1', '0', '6', '2')) ");
      //查询个人群组
//       sql.append(" or (exists (select 1 from oa_personal_group_user opgu where opgu.user_id=:userId and exists (select 1 from oa_meeting_apply_record_scope oms where oms.fieldDataValue=omar.attend_user and oms.scopeType='personalGroup' and oms.deleteflag=0 and oms.fieldData='attend_user' and oms.scopevalue=opgu.group_id)))");
       sql.append(")");
       if(StringUtils.isNotBlank(condition)){
           sql.append(" and omar.name like :condition ");
           paramMap.put("condition", "%"+condition+"%");
       }
       sql.append(" order by omar.start_time desc, omar.createdDate desc");
       if(StringUtils.isNotBlank(currentPage)){
           this.currentPageNum = Integer.valueOf(currentPage);
       }
       if(StringUtils.isNotBlank(pageSize)){
           this.pageSizeNum = Integer.valueOf(pageSize);
       }
       this.startLimitNum= (this.currentPageNum-1) * this.pageSizeNum;
       List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramMap, this.startLimitNum, this.pageSizeNum);

        if(list!=null && list.size()>0){
        	Locale localeCN = Locale.SIMPLIFIED_CHINESE;
            SimpleDateFormat format = new SimpleDateFormat("E",localeCN);
        	for(Map<String,Object> map : list){
                String startDateTime = String.valueOf(map.get("startDateTime"));
                String endDateTime = String.valueOf(map.get("endDateTime"));
                if(startDateTime != null){
                	String week = format.format(DateUtils.parseDate(startDateTime));
                    String day = DateUtils.formatDate(DateUtils.parseDate(startDateTime), "MM")+"."+DateUtils.formatDate(DateUtils.parseDate(startDateTime), "dd");
                    map.put("startTime", startDateTime.split(" ")[1]);
                    map.put("endTime", endDateTime.split(" ")[1]);
                    map.put("startDate", startDateTime.substring(5,startDateTime.length()));
                    map.put("endDate", endDateTime.substring(5,endDateTime.length()));
                    map.put("day", day);
                    map.put("week", week);
                }
            }
        }
        return list;
    }
    
    /**
     * 查询与我有关的所有周期会议
     * @param currentPage
     * @param pageSize
     * @param userId
     * @param corpId
     * @param condition 
     * @return
     */
    public List<Map> getCycleMeetingListOfMine(String currentPage, String pageSize, String userId,
            String corpId, String condition, String token) {
       StringBuffer sql = new StringBuffer();
       Map<String, Object> paramMap = new HashMap<String, Object>();
       paramMap.put("corpId", corpId);
       sql.append("select ar.cycle_id id,ar.name applyRecordName,ar.start_time startDateTime,ar.end_time endDateTime,mb.name boardroomName,ar.address,ar.boardroom_id boardroomId,su.user_name emcee_user,");
       sql.append(" ar.cycle_type cycleType,ar.cycle_end_time cycleEndTime,su.id emcee_user_id,ar.createdBy createdUserId");
       sql.append(" from oa_meeting_apply_record ar");
       sql.append(" join (select min( start_time ) start_time, cycle_id FROM oa_meeting_apply_record where is_cycle = 1 and cycle_id is not null group by cycle_id) t on ar.cycle_id=t.cycle_id and ar.start_time=t.start_time");
       sql.append(" left join oa_meeting_boardroom_set mb on ar.boardroom_id=mb.id");
       sql.append(" left join oa_meeting_apply_record_scope ms on ar.emcee_user = ms.fieldDataValue");
       sql.append(" left join sys_user su on su.id=ms.scopeValue");
       sql.append(" where ar.corp_id=:corpId and ar.is_sync=1");
       sql.append(" and (ar.createdBy=:userId ");
       sql.append("	or (ar.emcee_user IN (:emceeScopeList)");
       sql.append("		 or ar.memo_user IN (:memoScopeList)");
       sql.append("		 or ar.attend_user IN (:attendScopeList)))");
       List<String> scopelist = orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
       scopelist.add(userId);
       List<String> emceeScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", scopelist, "oa_meeting_apply_record", "emcee_user");
       List<String> memoScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", scopelist, "oa_meeting_apply_record", "memo_user");
       List<String> attendScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", scopelist, "oa_meeting_apply_record", "attend_user");
       paramMap.put("userId", userId);
       paramMap.put("emceeScopeList", CollectionUtils.isNotEmpty(emceeScopeList) ? emceeScopeList : "");
       paramMap.put("memoScopeList", CollectionUtils.isNotEmpty(memoScopeList) ? memoScopeList : "");
       paramMap.put("attendScopeList", CollectionUtils.isNotEmpty(attendScopeList) ? attendScopeList : "");
       if(StringUtils.isNotBlank(condition)){
           sql.append(" and ar.name like :condition ");
           paramMap.put("condition", "%"+condition+"%");
       }
       sql.append(" order by ar.start_time desc, ar.createdDate desc");
       if(StringUtils.isNotBlank(currentPage)){
           this.currentPageNum = Integer.valueOf(currentPage);
       }
       if(StringUtils.isNotBlank(pageSize)){
           this.pageSizeNum = Integer.valueOf(pageSize);
       }
       this.startLimitNum= (this.currentPageNum-1) * this.pageSizeNum;
       List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramMap, this.startLimitNum, this.pageSizeNum);

        if(list!=null && list.size()>0){
        	Locale localeCN = Locale.SIMPLIFIED_CHINESE;
            SimpleDateFormat format = new SimpleDateFormat("E",localeCN);
        	for(Map<String,Object> map : list){
                String startDateTime = String.valueOf(map.get("startDateTime"));
                String endDateTime = String.valueOf(map.get("endDateTime"));
                if(startDateTime != null){
                	String week = format.format(DateUtils.parseDate(startDateTime));
                    String day = DateUtils.formatDate(DateUtils.parseDate(startDateTime), "MM")+"."+DateUtils.formatDate(DateUtils.parseDate(startDateTime), "dd");
                    map.put("startTime", startDateTime.split(" ")[1]);
                    map.put("endTime", endDateTime.split(" ")[1]);
                    map.put("startDate", startDateTime.substring(5,startDateTime.length()));
                    map.put("endDate", endDateTime.substring(5,endDateTime.length()));
                    map.put("day", day);
                    map.put("week", week);
                }
            }
        }
        return list;
    }
    
    /**
     * 根据周期会议id查询周期会议
     * @param currentPage
     * @param pageSize
     * @param userId
     * @param corpId
     * @param condition
     * @param cycleId
     * @param token
     * @return
     */
    public List<Map> getCycleMeetingByCycleId(String currentPage, String pageSize, String userId,
            String corpId, String condition, String cycleId, String token) {
       StringBuffer sql = new StringBuffer();
       Map<String, Object> paramMap = new HashMap<String, Object>();
       sql.append("select omar.id,omar.name applyRecordName,omar.start_time startDateTime,omar.end_time endDateTime,omar.createdBy createdUserId,omar.is_signed,");
       sql.append("omar.signed_type,omar.status,su1.id emceeUserId,su1.user_name emceeUserName,su2.id memoUserId,");
       sql.append("ommi.id memoInfoId,ombs.name boardroomName,omar.address,omar.boardroom_id boardroomId,ombs.is_approve isApprove,omar.createdDate,ommui.is_view isView,:userId as userId ");
       sql.append("from oa_meeting_apply_record omar ");
       sql.append("left join oa_meeting_apply_record_scope oms1 on omar.emcee_user = oms1.fieldDataValue ");
       sql.append("left join sys_user su1 on oms1.scopeValue = su1.id ");
       sql.append("LEFT JOIN (select max(su.id) id, oms.fieldDataValue from oa_meeting_apply_record_scope oms ");
       sql.append("LEFT JOIN sys_user su on oms.scopeValue = su.id where oms.fieldData='memo_user' GROUP BY oms.fieldDataValue) su2 ");
       sql.append("ON omar.memo_user = su2.fieldDataValue ");
       sql.append("left join oa_meeting_boardroom_set ombs on omar.boardroom_id = ombs.id ");
       sql.append("left join oa_meeting_memo_info ommi on omar.id = ommi.apply_record_id ");
       sql.append("left join oa_meeting_memo_user_info ommui on ommi.id = ommui.memo_id and ommui.memo_user_id = :userId ");
       sql.append("where omar.corp_id =:corpId and omar.is_cycle=1 and omar.cycle_id=:cycleId and omar.is_sync=1");
       sql.append(" and omar.status not in ('-1', '0', '6', '2') ");
       if(StringUtils.isNotBlank(condition)){
           sql.append(" and omar.name like :condition ");
           paramMap.put("condition", "%"+condition+"%");
       }
       sql.append(" order by omar.start_time desc, omar.createdDate desc");
       paramMap.put("corpId", corpId);
       paramMap.put("userId", userId);
       paramMap.put("cycleId", cycleId);
       if(StringUtils.isNotBlank(currentPage)){
           this.currentPageNum = Integer.valueOf(currentPage);
       }
       if(StringUtils.isNotBlank(pageSize)){
           this.pageSizeNum = Integer.valueOf(pageSize);
       }
       this.startLimitNum= (this.currentPageNum-1) * this.pageSizeNum;
       List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramMap, this.startLimitNum, this.pageSizeNum);

        if(list!=null && list.size()>0){
        	Locale localeCN = Locale.SIMPLIFIED_CHINESE;
            SimpleDateFormat format = new SimpleDateFormat("E",localeCN);
        	for(Map<String,Object> map : list){
                String startDateTime = String.valueOf(map.get("startDateTime"));
                String endDateTime = String.valueOf(map.get("endDateTime"));
                if(startDateTime != null){
                	String week = format.format(DateUtils.parseDate(startDateTime));
                    String day = DateUtils.formatDate(DateUtils.parseDate(startDateTime), "MM")+"."+DateUtils.formatDate(DateUtils.parseDate(startDateTime), "dd");
                    map.put("startTime", startDateTime.split(" ")[1]);
                    map.put("endTime", endDateTime.split(" ")[1]);
                    map.put("startDate", startDateTime.substring(5,startDateTime.length()));
                    map.put("endDate", endDateTime.substring(5,endDateTime.length()));
                    map.put("day", day);
                    map.put("week", week);
                }
            }
        }
        return list;
    }
    
    public int deleteApplyRecord(List<String> ids){
        return this.dao.deleteApplyRecord(ids);
    }

    public List<ApplyRecordExport> getExportList(Map<String, Object> map){
    	WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        Map<String, String> param = new HashMap<String, String>();
        param.put("userId", user.getUserId());
        param.put("corpId", corpId);
        param.put("module", "meeting");
        param.put("type", "1,2");
        param.put("category", "meetingProgress");
        // 流程可查看人
        List<String> readList = new ArrayList<String>();
        try {
            // 查询当前用户具有查看流程的权限以及是否是流程管理员
            String principalName = restClient.post("/bpm/process/getProcessCodeByUserId", user.getJwtToken(), param);
            Map<String,Object> JsonMap = JsonUtils.readValue(principalName);
            if(JsonMap.get("type").toString().equals("success")){
                Map<String, Object> dataMap = (Map<String, Object>) JsonMap.get("data");
                // 流程可查看人的code
                readList = (List<String>) dataMap.get("viewList");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer(" ");
        String boardroomName = StringUtils.null2String(map.get("boardroomName"));
        String startTime = StringUtils.null2String(map.get("startTime"));
        String endTime = StringUtils.null2String(map.get("endTime"));
        String bpmStatus = StringUtils.null2String(map.get("bpmStatus"));

        sql.append("select omar.id,omar.name,omar.start_time startTime,omar.end_time endTime,omar.createdBy,omar.apply_user_name,omar.apply_org_name,");
        sql.append("omar.status,omar.remark,ombs.name boardroomName,omar.address,omar.boardroom_id boardroomId, omar.meeting_serve serveIds,arp.NAME_ as procName,ahp.END_TIME_ as bpmEndTime, ");
        sql.append("ahp.EXT_PROCESSSTATUS bpmStatus from oa_meeting_apply_record omar ");
        sql.append("left join oa_meeting_boardroom_set ombs on omar.boardroom_id = ombs.id ");
        sql.append(" join act_hi_procinst ahp on omar.id = ahp.BUSINESS_KEY_ ");
        sql.append("left join act_ru_variable arv on ahp.PROC_INST_ID_ = arv.PROC_INST_ID_ and arv.name_ = 'ext_indraft' ");
        sql.append(" join act_re_procdef arp on ahp.PROC_DEF_ID_ = arp.ID_ ");
        sql.append("where omar.corp_id =:corpId and ahp.PROC_INST_ID_ is not null and arv.ID_ is null ");
        paramMap.put("corpId", corpId);

        if (readList != null && readList.size() > 0) {
            sql.append(" and  arp.KEY_ in (:readList) ");
            paramMap.put("readList", readList);
        }else {
        	sql.append(" and arp.KEY_ in ('') ");
        }

        if(StringUtils.isNotBlank(boardroomName)){
            sql.append(" and ombs.name like :boardroomName ");
            paramMap.put("boardroomName", "%"+boardroomName+"%");
        }

        //开始结束时间
        if(StringUtils.isNotBlank(startTime)){
            sql.append(" and omar.start_time >= :startTime ");
            paramMap.put("startTime", startTime + " 00:00");
        }
        if(StringUtils.isNotBlank(endTime)){
            sql.append(" and omar.end_time <= :endTime ");
            paramMap.put("endTime", endTime + " 59:59");
        }
        
        if(StringUtils.isNotBlank(bpmStatus)){
            sql.append(" and ahp.EXT_PROCESSSTATUS = :bpmStatus ");
            paramMap.put("bpmStatus", bpmStatus);
        }

        //会议状态查询
//        if("0".equals(applyStatus)){//申请中
//            sql.append(" and ahp.END_TIME_ is null and omar.status = '0' ");
//        }else if("1".equals(applyStatus)){//未召开
//            sql.append(" and ahp.END_TIME_ is not null and omar.status = '1' ");
//        }else if("1".equals(applyStatus)){//已驳回
//            sql.append(" and ahp.END_TIME_ is null and omar.status = '2' ");
//        }else if("3".equals(applyStatus)){//已取消
//            sql.append(" and omar.status in ('-1', '3') ");
//        }else if("4".equals(applyStatus)){//进行中
//            sql.append(" and omar.status in ('4') ");
//        }else if("5".equals(applyStatus)){//已结束
//            sql.append(" and omar.status in ('5') ");
//        }

        sql.append("order by omar.start_time desc, omar.createdDate desc ");
        List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramMap);
        List<ApplyRecordExport> result = new ArrayList<>();
        if(list!=null && list.size()>0){
            for(int i=0; i<list.size(); i++){
                ApplyRecordExport export = new ApplyRecordExport();
                Map<String, Object> apply = list.get(i);
               // export.setName(StringUtils.null2String(apply.get("name")));
                export.setApplyUserName(StringUtils.null2String(apply.get("apply_user_name")));
                export.setApplyOrgName(StringUtils.null2String(apply.get("apply_org_name")));
                export.setStartTime(StringUtils.null2String(apply.get("startTime")));
                export.setEndTime(StringUtils.null2String(apply.get("endTime")));
                export.setRemark(StringUtils.null2String(apply.get("remark")));
                export.setBoardroomName(StringUtils.null2String(apply.get("boardroomName")));
                //会议服务
                String serveIds = StringUtils.null2String(apply.get("serveIds"));
                if(serveIds != ""){
                    String serveName = this.serveSetService.getServeName(serveIds);
                    export.setMeetingServe(serveName);
                }
                String _bpmStatus = StringUtils.null2String(apply.get("bpmStatus"));
                if("1".equals(_bpmStatus))
                	export.setBpmStatus("进行");
                else if("2".equals(_bpmStatus))
                	export.setBpmStatus("结束");
                else if("3".equals(_bpmStatus))
                	export.setBpmStatus("作废");
                else if("4".equals(_bpmStatus))
                	export.setBpmStatus("取消");
                //状态
//                String status = StringUtils.null2String(apply.get("status"));
//                if(apply.get("bpmEndTime") == null){//流程状态为进行中
//                    if("0".equals(status)){
//                        export.setStatus("申请中");
//                    }else if("-1".equals(status) || "3".equals(status)){
//                        export.setStatus("已取消");
//                    }else if("2".equals(status)){
//                        export.setStatus("已驳回");
//                    }
//                }else{
//                    if("1".equals(status)){
//                        export.setStatus("未召开");
//                    }else if("4".equals(status)){
//                        export.setStatus("进行中");
//                    }else if("5".equals(status)){
//                        export.setStatus("已结束");
//                    }else{
//                        export.setStatus("已取消");
//                    }
//                }
                result.add(export);
            }
        }
        return result;
    }
    
    /**
     * 查询流程标题
     * @param proId
     * @return
     */
    public String getTitleByProInsId(String proId){
        StringBuffer sb =new StringBuffer();
        sb.append("SELECT t.TEXT_ title FROM act_hi_varinst t ");
        sb.append("WHERE t.PROC_INST_ID_ =:proId AND t.NAME_='title' ");
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("proId", proId);
        List<Map> list=super.findByListNativeQuery(sb.toString(), "",paramMap);
        if(null!=list && list.size()>0){
          return list.get(0).get("title")+"";
        }
        return null;
    }
    
    /**
     * 替换会议记录人
     * @param applyRecordId
     * @param memoUserId
     * @param memoUserName
     * @return
     */
    public int changMemoUser(String applyRecordId, String memoUserId, String memoUserName) {
    	int result = 0;
    	ApplyRecord applyRecord = applyRecordService.findOne(applyRecordId);
    	if(applyRecord != null) {
    		List<String> mScopeList = new ArrayList<>();
            mScopeList.add(applyRecord.getMemoUser());
            //查询现在有记录人
            List<MeetingScope> memoUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
            if(memoUserList!=null && memoUserList.size()>0){
                MeetingScope ms = memoUserList.get(0);
                String oldMemoUserId = ms.getScopevalue();
                if(!StringUtils.equals(oldMemoUserId, memoUserId)){
                	String oldMemoUserName = ms.getName();
                    //原记录人变为普通参会人，如果已经在普通参会人员里就不添加
                	MeetingScope attendMs = this.meetingScopeService.getModelScope(oldMemoUserId, "oa_meeting_apply_record", "attend_user", applyRecord.getAttendUser());
                	if(attendMs == null)
                		saveMeetingScope(oldMemoUserId, oldMemoUserName, applyRecord, "attend_user");
                    result = this.meetingScopeService.updateScopeValue(memoUserId, memoUserName, ms.getId());
                }
            }else {
            	//新增记录人
            	saveMeetingScope(memoUserId, memoUserName, applyRecord, "memo_user");
            }
    	}
    	return result;
    }
    
    /**
     * 更改scope表中的人
     * @param userId
     * @param userName
     * @param applyRecord
     * @param fieldData
     * @return
     */
    public MeetingScope saveMeetingScope(String userId, String userName, ApplyRecord applyRecord, String fieldData) {
    	MeetingScope ms = new MeetingScope();
        ms.setScopetype("user");
        ms.setType("ID");
        ms.setScopevalue(userId);
        ms.setName(userName);
        ms.setFielddatatable("oa_meeting_apply_record");
		if(StringUtils.isNotBlank(applyRecord.getAttendUser())) {
			if("attend_user".equals(fieldData)) ms.setFielddatavalue(applyRecord.getAttendUser());
			else if("memo_user".equals(fieldData)) ms.setFielddatavalue(applyRecord.getMemoUser());
		}else {
			String scope = UuidUtils.UUID();
			ms.setFielddatavalue(scope);
			if("attend_user".equals(fieldData)) applyRecord.setAttendUser(scope);
			else if("memo_user".equals(fieldData)) applyRecord.setMemoUser(scope);
			applyRecordService.save(applyRecord);
		}
        ms.setFielddata(fieldData);
        ms.setDeleteflag("0");
        ms.setSortNo(0);
        return meetingScopeService.save(ms);
    }
    
}